﻿using HuiZe.education.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Windows;
using System.Windows.Controls;

namespace HuiZe.education.View
{
    /// <summary>
    /// PART_Lesson_Media_Host.xaml 的交互逻辑
    /// </summary>
    public partial class PART_ResourceItem_Media_Host : UserControl
    {
        public PART_ResourceItem_Media_Host()
        {
            InitializeComponent();
        }

        public void Load(respResourceChildModel _data)
        {
            Reset();
            _model_src = _data;
            _is_selected_default = false;
            if (_data == null) return;

        }

        void PART_CoursesResourceItem_Loaded(object sender, RoutedEventArgs e)
        {
            (sender as RadioButton).Checked += PART_CoursesResourceItem_Checked;
            if (!_is_selected_default)
            {
                _is_selected_default = true;
                (sender as RadioButton).IsChecked = new bool?(true);
            }
        }

        void PART_CoursesResourceItem_Checked(object sender, RoutedEventArgs e)
        {
            resKindItemModel _item = ((FrameworkElement)sender).DataContext as resKindItemModel;
            SetData(_item);
        }


        void PART_IsSelected_CoursesResourceItem_Loaded(object sender, RoutedEventArgs e)
        {

        }

        public void SetData(resKindItemModel _data, Action<bool> _callback_fullscreen = null)
        {
            _fullscreen_callback = _callback_fullscreen;

            Reset();

            if (_data == null)
            {
                return;
            }

            int _type = GetType(_data);
            if (_type < 0) return;

            _root_res = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Local");
            string _root_res_id = Path.Combine(_root_res, _data.id.ToString());
            if (!Directory.Exists(_root_res_id)) Directory.CreateDirectory(_root_res_id);

            switch (_type)
            {
                case 0:
                    PART_MP3.MP3Type = 0;
                    PART_MP3.Visibility = Visibility.Visible;
                    string _path_mp3 = Path.Combine(_root_res_id, Path.GetFileName(_data.file));
                    string _path_mp3_img = Path.Combine(_root_res_id, Path.GetFileName(_data.image));
                    PART_MP3.SetLyric(_data.resources_name != "单歌曲" ? _data.lyric_text : null);
                    if (_data.rotation_img_text == null || _data.rotation_img_text.Length == 0)
                    {
                        PART_MP3.SetImageList(null, 0);
                        if (!string.IsNullOrEmpty(_data.lyric_text))
                            PART_MP3.MP3Type = 1;
                    }
                    else
                    {
                        PART_MP3.MP3Type = 2;
                        var _tuples = new List<Tuple<string, string>>();
                        //foreach (string _img_url in _data.rotation_img_text)
                        //{
                        //    _tuples.Add(Tuple.Create(_img_url, Path.Combine(_root_res_id, Path.GetFileName(_img_url))));
                        //}
                        CheckDownload(_tuples.ToArray(), _success =>
                        {
                            PART_MP3.SetImageList(_tuples.Select(x => x.Item2).Where(x => File.Exists(x)).ToArray(), Convert.ToInt32(_data.rotation_times) / 1000);
                        });
                    }
                    if (File.Exists(_path_mp3_img))
                    {
                        PART_MP3.SetCorver(_path_mp3_img);
                    }
                    else
                    {
                        Download(_data.image, _path_mp3_img, _percentage =>
                        {

                        }, _success =>
                        {
                            PART_Dwonload_Progress.Value = 0;
                            PART_Dwonload_Progress.Maximum = 1;

                            PART_MP3.SetCorver(_path_mp3_img);
                        });
                    }
                    if (File.Exists(_path_mp3))
                    {
                        PART_MP3.SetMP3(_path_mp3);
                    }
                    else
                    {
                        Download(_data.file, _path_mp3, _percentage =>
                        {
                            PART_Dwonload_Progress.Maximum = 100;
                            PART_Dwonload_Progress.Value = _percentage;

                        }, _success =>
                        {
                            PART_Dwonload_Progress.Value = 0;
                            PART_Dwonload_Progress.Maximum = 1;
                            if (_success)
                                PART_MP3.SetMP3(_path_mp3);
                            else
                                PART_MP3.Reset();
                        });
                    }
                    break;
                case 1:
                    PART_Video.Visibility = Visibility.Visible;
                    string _path_mp4 = Path.Combine(_root_res_id, Path.GetFileName(_data.file));
                    if (File.Exists(_path_mp4))
                    {
                        PART_Video.SetVideo(_path_mp4, _fullscreen_callback);
                    }
                    else
                    {
                        Download(_data.file, _path_mp4, _percentage =>
                        {
                            PART_Dwonload_Progress.Maximum = 100;
                            PART_Dwonload_Progress.Value = _percentage;

                        }, _success =>
                        {
                            PART_Dwonload_Progress.Value = 0;
                            PART_Dwonload_Progress.Maximum = 1;
                            if (_success)
                                PART_Video.SetVideo(_path_mp4, _fullscreen_callback);
                            else
                                PART_Video.Reset();
                        });
                    }
                    break;
                case 2:
                    int _flash_type = 0;
                    PART_Flash.Visibility = Visibility.Visible;
                    //PART_Flash.SetFlash(_flash_type, _data.file);
                    string _path_flash = Path.Combine(_root_res_id, Path.GetFileName(_data.file));
                    if (File.Exists(_path_flash))
                    {
                        PART_Flash.SetFlash(_flash_type, _path_flash);
                    }
                    else
                    {
                        Download(_data.file, _path_flash, _percentage =>
                        {
                            PART_Dwonload_Progress.Maximum = 100;
                            PART_Dwonload_Progress.Value = _percentage;

                        }, _success =>
                        {
                            PART_Dwonload_Progress.Value = 0;
                            PART_Dwonload_Progress.Maximum = 1;

                            if (_success)
                                PART_Flash.SetFlash(_flash_type, _path_flash);
                            else
                                PART_Flash.Reset();
                        });
                    }
                    //if (_data.resources_name == "Flash")
                    //{
                    //    string _path_flash = Path.Combine(_root_res_id, Path.GetFileName(_data.file));
                    //    if (File.Exists(_path_flash))
                    //    {
                    //        PART_Flash.SetFlash(_flash_type, _path_flash);
                    //    }
                    //    else
                    //    {
                    //        Download(_data.file, _path_flash, _percentage =>
                    //        {
                    //            PART_Dwonload_Progress.Maximum = 100;
                    //            PART_Dwonload_Progress.Value = _percentage;

                    //        }, _success =>
                    //        {
                    //            PART_Dwonload_Progress.Value = 0;
                    //            PART_Dwonload_Progress.Maximum = 1;

                    //            PART_Flash.SetFlash(_flash_type, _path_flash);
                    //        });
                    //    }
                    //}
                    //else
                    //{
                    //    _flash_type = _data.resources_name == "swf压缩包" ? 1 : 2;
                    //    PART_Flash.SetFlash(_flash_type, _data.file);
                    //}
                    break;
                case 3:
                case 4:
                case 5:
                case 6:
                    //int _type_office = 0;
                    //if (_data.resources_name == "WORD") _type_office = 1;
                    //if (_data.resources_name == "PDF") _type_office = 2;
                    //if (_data.resources_name == "PPT") _type_office = 3;
                    PART_Office.Visibility = Visibility.Visible;
                    PART_Office.SetUrl(_data.file);
                    //string _path_office = Path.Combine(_root_res_id, Path.GetFileName(_data.file));
                    //if (File.Exists(_path_office))
                    //{
                    //    PART_Office.SetFile(_path_office, _type_office);
                    //}
                    //else
                    //{
                    //    Download(_data.file, _path_office, _percentage =>
                    //    {
                    //        PART_Dwonload_Progress.Maximum = 100;
                    //        PART_Dwonload_Progress.Value = _percentage;

                    //    }, _success =>
                    //    {
                    //        PART_Dwonload_Progress.Value = 0;
                    //        PART_Dwonload_Progress.Maximum = 1;

                    //        PART_Office.SetFile(_path_office, _type_office);
                    //    });
                    //}
                    break;
                case 7:
                    if (_data.file.Contains(";"))
                    {
                        PART_Images.Visibility = Visibility.Visible;
                        var _tuples = new List<Tuple<string, string>>();
                        string[] _images = _data.file.Split(';');
                        foreach (string _img_url in _images)
                        {
                            _tuples.Add(Tuple.Create(_img_url, Path.Combine(_root_res_id, Path.GetFileName(_img_url))));
                        }
                        CheckDownload(_tuples.ToArray(), _success =>
                        {
                            PART_Images.SetImageList(_tuples.Select(x => x.Item2).Where(x => File.Exists(x)).ToArray(), Convert.ToInt32(_data.rotation_times) / 1000, this.PART_LayoutRoot.ActualWidth, this.PART_LayoutRoot.ActualHeight);
                        });
                    }
                    else
                    {
                        PART_Photo.Visibility = Visibility.Visible;
                        string _path_photo = Path.Combine(_root_res_id, Path.GetFileName(_data.file));
                        if (File.Exists(_path_photo))
                        {
                            PART_Photo.SetPhoto(_path_photo);
                        }
                        else
                        {
                            Download(_data.file, _path_photo, _percentage =>
                            {
                                PART_Dwonload_Progress.Maximum = 100;
                                PART_Dwonload_Progress.Value = _percentage;

                            }, _success =>
                            {
                                PART_Dwonload_Progress.Value = 0;
                                PART_Dwonload_Progress.Maximum = 1;
                                if (_success)
                                    PART_Photo.SetPhoto(_path_photo);
                                else
                                    PART_Photo.Reset();
                            });
                        }
                    }
                    break;
                case 9:
                    PART_Html.Visibility = Visibility.Visible;
                    PART_Html.SetUrl(_data.file);
                    break;
            }
        }

        int GetType(resKindItemModel _data)
        {
            if (_data != null && !string.IsNullOrEmpty(_data.file))
            {
                string _ex = Path.GetExtension(_data.file);
                if (_ex.Length > 1) _ex = _ex.Substring(1).ToLower();
                if (!string.IsNullOrEmpty(_ex))
                {
                    if (_ex_mp3.Contains(_ex))
                        return 0;
                    if (_ex_video.Contains(_ex))
                        return 1;
                    if (_ex_flash.Contains(_ex))
                        return 2;
                    if (_ex_excel.Contains(_ex))
                        return 3;
                    if (_ex_word.Contains(_ex))
                        return 4;
                    if (_ex_pdf.Contains(_ex))
                        return 5;
                    if (_ex_ppt.Contains(_ex))
                        return 6;
                    if (_ex_img.Contains(_ex))
                        return 7;
                    if (_ex_txt.Contains(_ex))
                        return 8;
                    if (_ex_html.Contains(_ex))
                        return 9;
                }
            }
            return -1;
        }

        void CheckDownload(Tuple<string, string>[] _list, Action<bool> _callback)
        {
            if (_list == null || _list.Length == 0)
                return;

            new Thread(new ThreadStart(() =>
            {
                int _count_downloaded = 0;
                foreach (var _tuple in _list)
                {
                    if (!File.Exists(_tuple.Item2))
                    {
                        try
                        {
                            using (var _client = new WebClient())
                            {
                                _client.Proxy = null;
                                _client.DownloadFile(new Uri(_tuple.Item1, UriKind.RelativeOrAbsolute), _tuple.Item2);
                            }
                        }
                        catch (Exception ex)
                        {
                            App.Log(ex);
                        }
                    }
                    if (File.Exists(_tuple.Item2))
                        _count_downloaded++;
                }
                Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new Action(() =>
                {
                    _callback(_count_downloaded == _list.Length);
                }));
            }))
            { IsBackground = true }.Start();
        }

        void Download(string _url, string _path, Action<int> _progress_callback, Action<bool> _callback)
        {
            if (string.IsNullOrEmpty(_url) || string.IsNullOrEmpty(_path))
                return;

            new Thread(new ThreadStart(() =>
            {
                using (var _client = new WebClient())
                {
                    _client.Proxy = null;
                    _client.DownloadProgressChanged += (s, e) =>
                    {
                        Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new Action(() =>
                        {
                            _progress_callback(e.ProgressPercentage);
                        }));
                    };
                    _client.DownloadFileCompleted += (s, e) =>
                    {
                        if (e.Error != null)
                        {
                            App.Log(e.Error);
                        }
                        Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new Action(() =>
                        {
                            if (e.Cancelled || e.Error != null)
                            {
                                _callback(false);
                            }
                            else
                            {
                                _callback(true);
                            }
                        }));
                    };
                    _client.DownloadFileAsync(new Uri(_url, UriKind.RelativeOrAbsolute), _path);
                }
            }))
            { IsBackground = true }.Start();
        }

        public void Reset()
        {
            PART_MP3.Reset();
            PART_Video.Reset();
            PART_Flash.Reset();
            PART_Office.Reset();
            PART_Photo.Reset();
            PART_Html.Reset();
            PART_Images.Reset();
            PART_Dwonload_Progress.Value = 0;
            PART_Dwonload_Progress.Maximum = 1;
            PART_Html.Visibility = Visibility.Collapsed;
            PART_MP3.Visibility = Visibility.Collapsed;
            PART_Video.Visibility = Visibility.Collapsed;
            PART_Flash.Visibility = Visibility.Collapsed;
            PART_Office.Visibility = Visibility.Collapsed;
            PART_Photo.Visibility = Visibility.Collapsed;
            PART_Images.Visibility = Visibility.Collapsed;
        }

        string _root_res;
        Action<bool> _fullscreen_callback;
        string[] _ex_img = new string[]
        {
            "png", "jpg", "jpeg", "bmp", "gif"
        };
        string[] _ex_txt = new string[]
        {
            "txt"
        };
        string[] _ex_pdf = new string[]
        {
            "pdf"
        };
        string[] _ex_flash = new string[]
        {
            "swf"
        };
        string[] _ex_html = new string[]
        {
            "html"
        };
        string[] _ex_excel = new string[]
        {
            "xls", "xlsx"
        };
        string[] _ex_word = new string[]
        {
            "doc", "docx"
        };
        string[] _ex_ppt = new string[]
        {
            "ppt", "pptx"
        };
        string[] _ex_mp3 = new string[]
        {
            "aac", "ac3", "acm", "amr", "ape", "caf", "flac", "m4a", "mp3", "ra", "wav", "wma"
        };
        string[] _ex_video = new string[]
        {
            "3gp",
            "asf",
            "avi",
            "dat",
            "dv",
            "flv",
            "f4v",
            "gif",
            "m2t",
            "m3u8",
            "m4v",
            "mj2",
            "mjepg",
            "mkv",
            "mov",
            "mp4",
            "mpe",
            "mpg",
            "mpeg",
            "mts",
            "ogg",
            "qt",
            "rm",
            "rmab",
            "ts",
            "vob",
            "wmv",
            "webm",
        };


        bool _is_selected_default;
        respResourceChildModel _model_src;
    }
}
